package com.kalaqia.gradle.jiagu

import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.TaskAction

class JiaGu360Task extends DefaultTask {
    JiaGu360Extension configuration
    def android

    JiaGu360Task() {
        description = 'Assemble Resource Proguard APK'
        group = 'jiaGu360'
        outputs.upToDateWhen { false }
        android = project.extensions.android
        configuration = project.jiaGu360
        if (!project.plugins.hasPlugin('com.android.application')) {
            throw new GradleException('generateARGApk: Android Application plugin required')
        }
    }

    @SuppressWarnings("GroovyUnusedDeclaration")
    @TaskAction
    run() {
        project.logger.info("[JiaGu360] configuartion:$configuration")

        def isSupportChannel = configuration.isSupportChannel ? "1" : "0";

        //load sign properties
        Properties props = new Properties()
        props.load(new FileInputStream(configuration.getSignPropertiesFile()));

        String result = props.getProperty("keystore.path") + " " + props.getProperty("keystore.password") + " " + props.getProperty("signing.alias") + " " + props.getProperty("signing.password") + " ";

        if (configuration.getIsEnable()) {
            project.exec {
                ignoreExitValue true
                if (configuration.isMac) {
                    commandLine "sh", "${project.rootDir}/jiagu_mac/jiagu.sh", configuration.loadApk, configuration.outputApk, isSupportChannel
                } else {
                    commandLine "${project.rootDir}/jiagu/jiagu.bat", \
                            configuration.loadApk, configuration.outputApk, \
                            isSupportChannel, configuration.getJiaGuJarPath(), \
                            configuration.getAccount(), configuration.getPassword(), \
                            result
                }
            }
        }
    }
}
